package com.ulewo.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.ulewo.exception.BusinessException;
import com.ulewo.po.config.ConfigInfo;
import com.ulewo.po.enums.PageSize;
import com.ulewo.po.model.SolrBean;
import com.ulewo.po.vo.PaginationResult;
import com.ulewo.po.vo.SimplePage;
import com.ulewo.service.SolrService;

@Service
public class SolrServiceImpl implements SolrService {

    Logger logger = LoggerFactory.getLogger(SolrServiceImpl.class);
    @Resource
    private ConfigInfo configInfo;

    private static HttpSolrServer server = null;

    private HttpSolrServer getSolrServer() {
        if (server == null) {
            server = new HttpSolrServer(configInfo.getSolrServerUrl());
            server.setConnectionTimeout(configInfo.getSolrTimeOut());
            server.setDefaultMaxConnectionsPerHost(configInfo.getMaxConnectionsPerHost());
            server.setMaxTotalConnections(configInfo.getMaxTotalConnections());
        }
        return server;
    }

    @Override
    @Async
    public void addArticle(SolrBean bean) {
        logger.info("开始写入solr");
        if (!configInfo.isOpenSolr()) {
            return;
        }
        try {
            server = getSolrServer();
            server.addBean(bean);
            server.optimize();
            server.commit();
        } catch (Exception e) {
            logger.error("写入solr异常，SolrServer异常", e);
        }
    }

    @Override
    public void addArticleBatch(List<SolrBean> list) {
        try {
            server = getSolrServer();
            server.addBeans(list);
            server.optimize();
            server.commit();
        } catch (IOException e) {
            logger.error("批量写入solr异常，IO异常", e);
        } catch (SolrServerException e) {
            logger.error("批量写入solr异常，SolrServer异常", e);
        }
    }

    @Override
    public PaginationResult<SolrBean> selectArticle(String keyword, String articleType, Integer pageNo, Integer countTotal) throws BusinessException {
        final int MAX_LENG = 20;
        countTotal = countTotal == null ? 0 : countTotal;
        if (StringUtils.isEmpty(keyword) || keyword.trim().length() > MAX_LENG || StringUtils.isEmpty(articleType)) {
            throw new BusinessException("请求参数错误");
        }
        SolrQuery solrQuery = new SolrQuery();
        SimplePage page = new SimplePage();
        solrQuery.set("q", "(title:" + keyword + " OR content:" + keyword + ") AND articleType:" + articleType);
        if (pageNo == null || pageNo == 1) {
            solrQuery.setStart(0);
            solrQuery.setRows(PageSize.SIZE20.getSize());
        } else {
            page = new SimplePage(pageNo, countTotal, PageSize.SIZE20.getSize());
            solrQuery.setStart(page.getStart());
            solrQuery.setRows(page.getEnd());
        }
        //高亮
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("title");
        solrQuery.setHighlightSimplePre("<span class=\"red\">");
        solrQuery.setHighlightSimplePost("</span>");
        server = getSolrServer();
        QueryResponse response = null;
        try {
            response = server.query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        PaginationResult<SolrBean> result = new PaginationResult<SolrBean>();
        if (null != response) {
            int totalCount = (int) response.getResults().getNumFound();
            page.setCountTotal(totalCount);
            List<SolrBean> resultList = response.getBeans(SolrBean.class);
            Map<String, Map<String, List<String>>> map = response.getHighlighting();
            for (SolrBean bean : resultList) {
                Map<String, List<String>> values = map.get(bean.getId());
                if (values != null) {
                    List<String> titles = values.get("title");
                    if (titles != null && !titles.isEmpty()) {
                        bean.setTitle(titles.get(0));
                    }
                }
            }
            result = new PaginationResult<SolrBean>(page, resultList);
        }
        return result;
    }
}
